package com.hxtec.polaris.commons.thread;

import io.searchbox.client.JestClient;
import io.searchbox.core.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 浏览商品热度更新
 */
@Transactional
public class UpdateHotScoreRunable implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(UpdateHotScoreRunable.class);
    private ServletContext context = null;
    private CountDownLatch doneSignal;
    private String spuId;
    private JestClient jestClient;
    private RedisTemplate redisTemplate;

    public UpdateHotScoreRunable(ServletContext context, CountDownLatch doneSignal, String spuId){
        this.context = context;
        this.doneSignal = doneSignal;
        this.spuId=spuId;
    }

    @Override
    public void run() {
        initBean(context);
        try {
            synchronized(doneSignal){
                this.incrHotScore(spuId);
            }
            doneSignal.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取bean
     * @param context
     */
    private void initBean(ServletContext context){
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        this.jestClient = webApplicationContext.getBean(JestClient.class);
        this.redisTemplate = webApplicationContext.getBean(StringRedisTemplate.class);
    }

    //更新热度评分
    public void incrHotScore(String spuId){
        int timesToEs=100;
        Double hotScore = redisTemplate.opsForHash().increment("hotScore","spuId:" + spuId,1.0);
        if(hotScore%timesToEs==0){
            String updateJson="{\n" +
                    "   \"doc\":{\n" +
                    "     \"hotScore\":"+hotScore+"\n" +
                    "   }\n" +
                    "}";

            Update update = new Update.Builder(updateJson).index("hxtec").type("spuList").id(spuId).build();
            try {
                jestClient.execute(update);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
